package cn.itguy.mobileguard.service;

import cn.itguy.mobileguard.Constant;
import cn.itguy.mobileguard.GuardDetector;
import cn.itguy.mobileguard.GuardDetector.DetectorEventListener;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

public class IGuardService extends Service implements DetectorEventListener {

	private GuardDetector detector;
	
	private WakeLock wakeLock;

	private VolumeChangedReceiver receiver;

	@Override
	public void onCreate() {
		super.onCreate();
		if (Constant.DEBUG) {
			Log.d("IGuardService", "onCreate");
		}

		acquireWakeLock();
		
		IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        registerReceiver(screen_off_receiver, filter);
		
		detector = new GuardDetector(this);
		detector.setDetectorEventListener(this);
		detector.registerSensor();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (Constant.DEBUG) {
			Log.d("IGuardService", "onStartCommand");
		}
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (Constant.DEBUG) {
			Log.d("IGuardService", "onDestroy");
		}

		detector.shutdown();

		if (receiver != null) {
			unregisterReceiver(receiver);
			receiver = null;
		}
		
		unregisterReceiver(screen_off_receiver);
		
		releaseWakeLock();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	private BroadcastReceiver screen_off_receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            	detector.unregisterSensor();
            	detector.registerSensor();
            }
        }
    };
	
	private void acquireWakeLock() {
		PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
		int flags = PowerManager.PARTIAL_WAKE_LOCK;
		wakeLock = powerManager.newWakeLock(flags, "IGuardService");
		wakeLock.acquire();
	}
	
	private void releaseWakeLock() {
		if (wakeLock == null) {
			return;
		}
		if (wakeLock.isHeld()) {
			wakeLock.release();
		}
		wakeLock = null;
	}

	private class VolumeChangedReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			detector.turnUpToMaxVolume();
		}
	};

	@Override
	public void onStartAlarmError() {
		
	}

	@Override
	public void onAlarmStarted() {
		receiver = new VolumeChangedReceiver();
		registerReceiver(receiver, new IntentFilter(
				Constant.ACTION_VOLUME_CHANGED));
	}

}
